package cae.logic.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import cae.logic.destination.CaeDestination;


public class CaeFileSender {

	public static final int BUFFER_SIZE = 1024 * 50;
	
		
	public static boolean sendFile(String filePath, String fileName, CaeDestination destination) throws UnknownHostException, IOException, ClassNotFoundException
	{
		boolean operationOk = false;
		byte[] buffer = new byte[BUFFER_SIZE];
		Socket socket = new Socket(destination.getMachine()[0], destination.getFilePort());
		
		CaeFileInfo fileInfo = new CaeFileInfo(fileName);
		ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
		oos.writeObject(fileInfo);
		
		ObjectInputStream iis = new ObjectInputStream(socket.getInputStream());
		CaeFileAck ack = (CaeFileAck)iis.readObject();
		if(ack.isAccept())
		{
			BufferedOutputStream out = 
				new BufferedOutputStream(socket.getOutputStream());
	
			BufferedInputStream in = 
				new BufferedInputStream(
					new FileInputStream(filePath));
			
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
				System.out.print("#");
			}
			operationOk = true;
			in.close();
			out.flush();
			out.close();
		}
		socket.close();
		return operationOk;
	}
}
